//
//  FavModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/26/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import Foundation


final class FavModel {
    
    var favorites: [Fav] = []
    
    let backend = Backend()
    
    public func getPosts (request: URLRequest?=nil, completion: @escaping (Result<Response<[Fav]>, RequestError>) -> Void) {
        var postRequest: URLRequest!
        
        if (request != nil) {
            postRequest = request!
        } else {
            postRequest = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/favourites/"))
        }
        
        backend.fetchFromBackend(for: Response<[Fav]>.self, request: postRequest, statusCode: 200) { (result) in
            switch result {
            case .failure(let error):
                switch error {
                case .general:
                    completion(.failure(.general))
                case .parameter(let message):
                    completion(.failure(.parameter(message)))
                }
            case .success(let response):
                if request != nil {
                    
                    self.favorites += self.makeAllLiked(response.results)
                } else {
                    self.favorites = self.makeAllLiked(response.results)
                }
                completion(.success(response))
            }
        }
    }
    
    private func makeAllLiked (_ favs: [Fav]) -> [Fav] {
        var items = favs
        if items.count != 0 {
            for i in 0...items.count - 1 {
                items[i].advert.isLiked = true
            }
        }
        return items
    }
}
